-- table 通用函数定义

import "Scripts/base/define.lua";

local Value = Value; 
local Type = Type; 
local Function = Function; 
local Var = Var;

local table = table;
local table_inRange = table.inRange;
local string = string;

CopyValue = {
	["number"]		= CopyVar,
	["string"]		= CopyVar,
	["boolean"]		= CopyVar,
	["function"]	= CopyVar,
	["userdata"]	= CopyVar,
	["table"]		= CopyTable,
}

function CopyVar(v)
	return v;
end

function CopyTable(val)
	local tb = {};
	if val.__name and table_inRange(Classes, val.__name) then
		local elementType = val.__elementType or nil;
		tb = Classes[val.__name].new(elementType);
		tb:__copyobj(val);

		return tb;
	end

	for k, v in pairs(val) do
		local keyType = type(k);
		local valType = type(v);
		tb[k] = CopyValue[keyType](v);
	end

	return tb;
end

function table.vectorcopy(t)
  local t2 = {}
  for k,v in ipairs(t) do
    table.insert(t2, v)
  end
  return t2
end

function table.clone(src)
	local ret = {}
	for k,v in pairs(src) do
		local typek = type(k)
		assert(typek == "string" or typek == "number")
		local typev = type(v)
		if typev ~= "table" then
			ret[k] = v
		elseif typev == "userdata" then
			ret[k] = v
		else
			ret[k] = table.clone(v)
		end
	end
	return ret
end

-- 深度克隆，包括metatable也复制设置
function table.deepClone(src)
	local ret = {}
	for k,v in pairs(src) do
		local typek = type(k)
		assert(typek == "string" or typek == "number")
		local typev = type(v)
		if typev ~= "table" then
			ret[k] = v
		elseif typev == "userdata" then
			ret[k] = v
		else
			ret[k] = table.deepClone(v)
			if getmetatable(v) then
				setmetatable(ret[k] , getmetatable(v))
			end
		end
	end
	return ret
end

function table.merge(src, dst)
	for k,v in pairs(src) do
		local typek = type(k)
		assert(typek == "string" or typek == "number")
		if type(v) ~= "table" then 
			dst[k] = v
		elseif typev == "userdata" then
			dst[k] = v
		else
			dst[k] = table.clone(v)
		end
	end
	return s
end

function table.find(t, v)	
	assert(type(t) == "table")
     for k, value in pairs(t) do 
        if value == v then
			return k
		end
    end 
    return nil 
end

--用于那些不是顺序数组的table获得size
function table.hashcount(t)
	local count = 0
	for k in pairs(t) do count = count + 1 end
	return count
end